#include "TcpClient.h"
#include "innertype.h"
#include <QDebug>
#include "BridgeTool.h"
TcpClient::TcpClient(QObject *parent): QObject(parent)
{
    m_socket = new QTcpSocket;
}

void TcpClient::connect(QString ip,quint16 port)
{
    m_socket->connectToHost(ip, port,QTcpSocket::ReadWrite);
    QObject::connect(this->m_socket,SIGNAL(connected()),this,SLOT(connected()));
    QObject::connect(this->m_socket,SIGNAL(readyRead()),this,SLOT(readyread()));
    LOGAPI()<<"test qWarning";

}

void TcpClient::connected()
{
    // 链接成功
    qDebug()<<" connect success ! ";
    emit connectStatus(1);
}

void TcpClient::readyread(){
    // 消息可读取
    qDebug()<<" readyread ! ";
    emit readable();

}

bool TcpClient::sendMessage(QString sendStr)
{
    if (!m_socket->isOpen())
    {
        // 关闭了
        emit noticeMsg("System" , "网络已断开 , 请重新链接!");
        return  false;
    }
    std::string hexdata = HexToString(sendStr.toStdString());

    if(m_socket->write(sendStr.toLatin1().data(),strlen(sendStr.toLatin1().data())))
    {
        return true;
    }
    else {
        return false;
    }
}


bool TcpClient::sendHexMessage(QString sendStr)
{
    if (!m_socket->isOpen())
    {
        // 关闭了
        emit noticeMsg("System" , "网络断开 , 请重新链接!");
        return  false;
    }
    std::string hexdata = HexToString(sendStr.toStdString());

    LOGAPI()<<"sendHexMessage : "<< sendStr;

    if(m_socket->write(hexdata.c_str(),hexdata.length()))
    {
        return 1;
    }
    else {
        return 0;
    }
}
QString TcpClient::receiveMesage()
{
    QByteArray recvData = m_socket->readAll();
    // proc
    std::string buffer = recvData.toStdString();
    procMesage(buffer);

    return recvData;

}

void TcpClient::closeconnect()
{
    m_socket->close();
}

void TcpClient::procMesage(std::string &message)
{
    //    qDebug()<<"recv : "<<message;
    BridgeTool::TcpRecvCallback(message , [](QString title ,QString body , void *userdata){
        TcpClient* This = (TcpClient*)userdata;
        qDebug()<<"callback  title =" << title <<" , body = " << body ;
        This->noticeMsg(title, body);
    } , this);
}


TcpClient::~TcpClient()
{
    if(m_socket->isOpen())
    {
        m_socket->disconnectFromHost();
    }
    delete m_socket;

}
